package Pet.Management.repository;

import Pet.Management.domain.entity.ChatMessage;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

@Repository
public interface ChatMessageRepository extends JpaRepository<ChatMessage, Long> {
    // 获取用户的聊天记录
    Page<ChatMessage> findByUserIdOrderByCreateTimeDesc(Long userId, Pageable pageable);
    
    // 获取管理员的聊天记录
    Page<ChatMessage> findByAdminIdOrderByCreateTimeDesc(Long adminId, Pageable pageable);
    
    // 获取用户和管理员之间的聊天记录
    @Query("SELECT c FROM ChatMessage c WHERE (c.userId = ?1 AND c.adminId = ?2) OR (c.userId = ?2 AND c.adminId = ?1) ORDER BY c.createTime DESC")
    Page<ChatMessage> findConversation(Long userId, Long adminId, Pageable pageable);
    
    // 标记消息为已读
    @Modifying
    @Query("UPDATE ChatMessage c SET c.isRead = true WHERE c.id = ?1")
    void markAsRead(Long messageId);
    
    // 获取未读消息数量
    long countByUserIdAndIsRead(Long userId, Boolean isRead);
    
    // 获取管理员的未读消息数量
    long countByAdminIdAndIsRead(Long adminId, Boolean isRead);
} 